package com.dp.appi.controller;

import com.dp.appi.dao.ExplorationDao;
import com.dp.appi.entity.UserEntity;
import com.dp.appi.exception.PackageRuntimeException;
import com.dp.appi.exception.ProjectRuntimeException;
import com.dp.appi.service.ConsumerService;
import com.dp.appi.service.PackageService;
import com.dp.appi.util.*;
import com.dp.appi.util.ExceptionUtil;
import com.dp.appi.util.SYS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipFile;

/**
 * Created by Administrator on 2016/8/25.
 */
@Controller
@RequestMapping(value = "/packageControl")
public class PackageControl {
    private static Logger log = LoggerFactory.getLogger(PackageControl.class);

    @Autowired
    private PackageService packageService;

    @Autowired
    private ExplorationDao explorationDao;

    @Value("${offline_package_upload_path}")
    private String offline_package_upload_path;//离线包上传路径

    @Value("${offline_package_down_path}")
    private String offline_package_down_path;//离线包下载打包存储路径

    @Value("${offline_package_down_server}")
    private String offline_package_down_server;//离线包下载包服务路径

    @Value("${file_path}")
    private String file_path;

    @Autowired
    private ConsumerService consumerService;

    /**
     * 项目数据包
     *
     * @param modelMap
     * @param req
     * @param param
     */
    @RequestMapping(value = "/projectPackage", method = RequestMethod.GET)
    public void projectPackage(ModelMap modelMap, HttpServletRequest req, @RequestParam Map<String, String> param) {
        String rootPath = this.offline_package_down_path;
        String serverPath = this.offline_package_down_server;

        String openIdent = param.get("openIdent");
        UserEntity userEntity = UserEntity.decrypt(openIdent);
        Map<String, Object> map = (Map<String, Object>) consumerService.getUser(userEntity);
        String id = map.get("id").toString();

        Long stageId = Long.valueOf(param.get("stageId"));

        Integer classify = explorationDao.getClassify(stageId, id);


        try {
            String zipName = packageService.projectPack(rootPath, param, classify);
            System.out.println(serverPath + zipName);
            modelMap.addAttribute("zipPath", serverPath + zipName);
        } catch (ProjectRuntimeException e) {
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

/*******************************xjs********************************************/
    /**
     * 离线上传
     *
     * @param modelMap 返回数据
     * @param param    提交参数
     * @param request  请求对象
     * @param file     离线压缩包
     */
    @RequestMapping(value = "/offlineUpload", method = RequestMethod.POST)
    public void offlineUpload(ModelMap modelMap, @RequestParam Map<String, String> param,
                              HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        try {
            String stageId =param.get("stage_id");

            //判断目录是否存在 不存在创建
            String _path = offline_package_upload_path + DateUtil.getNowDateStr() + "/";
            File f = new File(_path);
            if (!f.exists()) {
                f.mkdirs();
            }

            String filename = file.getOriginalFilename();
            File targetFile = new File(_path + filename);
            //是文件且存在,存在文件
            Integer classify = null;

            String[] _files = filename.split("\\.");
            String suffix = _files[1];//后缀
            String prefix = _files[0];//前缀
//            targetFile.isFile() && targetFile.exists()
            if (targetFile.exists()) {
                FileUtil fileUtil = new FileUtil();
                fileUtil.deleteFile(_path + filename);//删除已经存在的压缩文件
                fileUtil.deleteDirectory(_path + prefix);//删除解压后的压缩文件路径
            }
                //上传文件
                file.transferTo(targetFile);
                //解压
                CompressFile.unZipFiles(targetFile, _path);
                //获取用户信息
                String openIdent = param.get("openIdent");
                UserEntity userEntity = UserEntity.decrypt(openIdent);
                Map<String, Object> map = (Map<String, Object>) consumerService.getUser(userEntity);
                String id = map.get("id").toString();

                //遍历文件夹,成功后返回阶段id
                Long stage_id = packageService.analysisPackage(_path + prefix,stageId,id);


                //数据解包存储后对阶段踏勘点角度重新计算
                classify = explorationDao.getClassify(stage_id, id);

                List<Map<String, Object>> list = packageService.explorationList(stage_id, null, classify);
                for (int i = 0; i < list.size(); i++) {
                    Long pex_id = Long.valueOf(list.get(i).get("exploration_id").toString());
                   if( null !=list.get(i).get("before_exp") )
                    {
                        String  new_before_exp_id =list.get(i).get("before_exp").toString();

                        explorationDao.upjckyExploration(pex_id,Long.parseLong(String.valueOf(new_before_exp_id) ));
                    }
                    String pt_type = list.get(i).get("pt_type").toString();
                    if (pt_type.equals("11")) {
                        packageService.calculateConer(pex_id);
                    }
//
                    Long pt_id = Long.valueOf(list.get(i).get("pt_id").toString());
                    if(pt_id==100002){
                        //更新自己为台区并更新下联中所有点位台区为自己
                        packageService.up_explor_byBYQID(pex_id,pex_id);
                    }
                }

                //数据处理完毕后重新打包返回数据包给客户端
                param.put("stageId", String.valueOf(stage_id));


//            packageService.analysisPackage("F:\\zip\\OpenIdent\\OpenIdent");//测试
//            modelMap.addAllAttributes(SYS.SUCCESS.msgMap());

            String rootPath = this.offline_package_down_path;
            String serverPath = this.offline_package_down_server;
            String zipName = packageService.projectPack(rootPath, param, classify);
//            modelMap.addAttribute("zipPath", serverPath + zipName);

            modelMap.addAttribute("zipPath", serverPath + zipName);
        } catch (PackageRuntimeException e) {
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
            e.printStackTrace();
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
            e.printStackTrace();
        }
    }

//    /*******************************xjse********************************************/
//    @RequestMapping(value = "/up_explor_id", method = RequestMethod.GET)
//    public void up_explor_id(ModelMap modelMap, HttpServletRequest req, @RequestParam Map<String, String> param) {
//        try {
//            Long exploration_id = Long.valueOf(param.get("exploration_id"));
//            packageService.up_explor_byBYQID(exploration_id);
//        } catch (ProjectRuntimeException e) {
//            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
//        } catch (Exception e) {
//            modelMap.addAllAttributes(SYS.E10002.msgMap());
//            log.error(ExceptionUtil.getExceptionAllinformation(e));
//        }
//    }

}
